package cn.icatw.wallpaperapi.controller;

import cn.icatw.wallpaperapi.common.R;
import cn.icatw.wallpaperapi.domain.Collect;
import cn.icatw.wallpaperapi.domain.vo.CollectVo;
import cn.icatw.wallpaperapi.service.CollectService;
import cn.icatw.wallpaperapi.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author icatw
 * @date 2022/10/16
 * @email 762188827@qq.com
 * @apiNote
 */
@RestController
@Api("前台收藏模块")
@RequestMapping("/api/collect")
@Slf4j
public class FrontCollectController {
    @Resource
    CollectService collectService;
    @Resource
    JwtUtil jwtUtil;

    @GetMapping("page")
    @ApiOperation("获取用户收藏列表")
    public R pageList(HttpServletRequest request, @RequestParam int current, @RequestParam int size) {
        Page<CollectVo> page = new Page<>(current, size);
        String userId = jwtUtil.getClaimByToken(request);
        IPage<CollectVo> iPage = collectService.pageList(page, userId);
        return R.ok(iPage);
    }

    @PostMapping("love/{imageId}")
    @ApiOperation("收藏/取消收藏图片")
    public R love(@PathVariable int imageId, HttpServletRequest request) {
        String userId = jwtUtil.getClaimByToken(request);
        if (StringUtils.isEmpty(userId)) {
            return  R.fail("请先登陆！");
        }
        Collect collect = collectService.getOne(new QueryWrapper<Collect>()
                .eq("user_id", userId)
                .eq("image_id", imageId));
        if (collect != null) {
            //如果查询到了收藏信息，则设置状态为相反
            collect.setStatus(collect.getStatus() == 1 ? 0 : 1);
            return R.ok(collectService.updateById(collect));
        }
        Collect userCollect = new Collect();
        userCollect.setUserId(Integer.valueOf(userId));
        userCollect.setImageId(imageId);
        userCollect.setStatus(1);
        return R.ok(collectService.save(userCollect));
    }
}
